package com.RKB.web;

import com.RKB.service.AnswerResultService;
import com.RKB.service.UserService;
import com.RKB.api.AjaxResult;
import com.RKB.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@CrossOrigin //允许跨域请求 springboot原生不支持跨域。
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private AnswerResultService answerResultService;

    /**
     * 注册用户
     * @param
     * @return
     */
    @RequestMapping("/addUser")
    public AjaxResult<String> addUser(@RequestBody User user){
        List<User> list = userService.findByUsername(user);
        //System.out.println("这是list"+list);
        //System.out.println(user);

        if(user.getUsername()==""||user.getUsername()==null){
            AjaxResult<String> result = new AjaxResult<>();
            result.setCode(300);
            result.setMsg("未输入账号");
            result.setData("未输入账号");
            return result;
        }
        if(!list.isEmpty()){
            AjaxResult<String> result = new AjaxResult<>();
            result.setCode(300);
            result.setMsg("用户名重复，创建用户失败");
            result.setData("用户名重复，创建用户失败");
            return result;
        }
       userService.addUser(user);
        AjaxResult<String> result = new AjaxResult<>();
        result.setCode(200);
        result.setMsg("成功创建用户");
        result.setData("创建用户成功");
        System.out.println("successful");
        answerResultService.initializationUserAnalysis(user.getUsername());  //  初始化用户的答题结果分析
        return result;
    }

    /**
     * 用户登录
     * @param
     * @return
     */
    @RequestMapping("/signUser")
    public AjaxResult<List> signUser(@RequestBody User user){
        List<User> usr = userService.signUser(user);
        if(usr.isEmpty()) {
            AjaxResult<List> result = new AjaxResult<>();
            result.setCode(300);
            result.setMsg("登录失败，账号/密码 错误");
            result.setData(usr);
            return result;
        }

        AjaxResult<List> result = new AjaxResult<>();
        result.setCode(200);
        result.setMsg("登录成功");
        result.setData(usr);
        return result;
    }

}
